package cn.daichi.redisidempotency.service.impl;

import cn.daichi.redisidempotency.common.Constant;
import cn.daichi.redisidempotency.common.HttpMsg;
import cn.daichi.redisidempotency.exception.IdempotencyException;
import cn.daichi.redisidempotency.service.IdempotencyService;
import cn.daichi.redisidempotency.utils.RedisUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Service
public class IdempotencyServiceImpl implements IdempotencyService {

    private final RedisUtil redisUtil;

    public IdempotencyServiceImpl(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }


    @Override
    public String createIdempotencyToken() {
        String token = Constant.IDEMPOTENCY_PREFIX + UUID.randomUUID().toString(true);
        if (!redisUtil.setEx(token, new Date().toString(), 60 * 1000)) {
            throw new IdempotencyException("创建token失败");
        }
        return token;
    }

    @Override
    public boolean checkIdempotency(HttpServletRequest request) {
        String header = request.getHeader(Constant.IDEMPOTENCY_HEADER);
        if (StrUtil.isBlank(header)) {
            throw new IdempotencyException(HttpMsg.REPEAT_OPERATION);
        }
        if (!redisUtil.remove(header)) {
            throw new IdempotencyException(HttpMsg.REPEAT_OPERATION);
        }
        return true;
    }


}
